#include <boost/filesystem.hpp>
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <longnam.h>
#include <fitsio.h>
#include "ExtractWCS.h"

using namespace boost::filesystem;
using namespace std;

typedef vector<string> StringVec;

void extract_center(const char* filepath, double& ra, double &dec) {
    int status(0);
    fitsfile* fitsptr;

    fits_open_file(&fitsptr, filepath, 0, &status);
    fits_read_key(fitsptr, TDOUBLE, "CRVAL1", &ra,  NULL, &status);
    fits_read_key(fitsptr, TDOUBLE, "CRVAL2", &dec, NULL, &status);
    fits_close_file(fitsptr, &status);
}

void ExtractWCS(const char* dirName) {
    path pathDir(dirName);
    directory_iterator itend = directory_iterator();
    char temp[100];
    char seps[] = "_-";
    char *token;
    int azi, alt;
    double ra, dec;

    StringVec files;
    for (directory_iterator it = directory_iterator(pathDir); it != itend; ++it) {
        string extname = it->path().extension().string();
        if (extname != ".wcs") continue;
        files.push_back(it->path().string());
    }
    stable_sort(files.begin(), files.end());

    for (auto &it : files) {
        string filename = path(it).stem().string();
        strncpy(temp, filename.c_str(), 100);
        token = strtok(temp, seps);
        azi = atoi(token);
        token = strtok(NULL, seps);
        alt = atoi(token);
        if (filename[0] == '_') azi = -azi;

        extract_center(it.c_str(), ra, dec);

        printf ("%4d %2d %9.5lf %9.5lf\n", azi, alt, ra, dec);
    }
}
